package com.pf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pf.dto.AddUserReq;
import com.pf.mapper.UserMapper;
import com.pf.mapper.entity.User;
import com.pf.service.UserService;
import com.pf.utils.AESUtils;
import com.pf.utils.DTOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertUser(AddUserReq req) {
        User user = DTOUtils.copyToNewObj(req, User.class);
        user.setMobileCipher(AESUtils.encrypt(req.getMobile(), AESUtils.AES_KEY));
        user.setIdCardCipher(AESUtils.encrypt(req.getIdCard(), AESUtils.AES_KEY));
        user.setCreatedBy("system");
        user.setCreatedByCipher(AESUtils.encrypt("system", AESUtils.AES_KEY));
        user.setCreatedTime(new Date());
        user.setUpdatedBy("system");
        user.setUpdatedByCipher(AESUtils.encrypt("system", AESUtils.AES_KEY));
        user.setUpdatedTime(new Date());
        userMapper.insert(user);
    }

    @Override
    public List<User> getAllUser() {
        return userMapper.selectList(
                new LambdaQueryWrapper<User>()
                        .eq(User::getIsDeleted, 0)
        );
    }

    @Override
    public User getUserByMobile(String mobile) {
        return userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getMobile, mobile));
    }
}
